import os
import glob

root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

def remove_bom(file_path):
    """检查并移除文件的BOM标记"""
    try:
        with open(file_path, 'rb') as f:
            content = f.read()
        
        # 检查是否UTF-8 BOM
        if content.startswith(b'\xef\xbb\xbf'):
            # 移除BOM并重新写入
            content_without_bom = content[3:]
            with open(file_path, 'wb') as f:
                f.write(content_without_bom)
            print(f"Removed BOM: {os.path.relpath(file_path, root)}")
            return True
        else:
            print(f"No BOM: {os.path.relpath(file_path, root)}")
            return False
    except Exception as e:
        print(f"Error: {os.path.relpath(file_path, root)} - {e}")
        return False

def check_directory_for_bom(directory):
    """检查目录中所有文件的BOM"""
    # 查找所有文件
    all_files = []
    for pattern in ["**/*.sh", "**/*.bat", "**/*.py", "**/*.md", "**/*.yml", "**/*.yaml", "**/*.xml", "**/*.java", "**/*.properties"]:
        all_files.extend(glob.glob(os.path.join(directory, pattern), recursive=True))
    
    fixed_count = 0
    total_count = len(all_files)
    
    for file_path in all_files:
        if os.path.isfile(file_path):
            if remove_bom(file_path):
                fixed_count += 1
    
    print(f"\nSummary:")
    print(f"Total files: {total_count}")
    print(f"Files with BOM removed: {fixed_count}")

if __name__ == "__main__":
    print("Checking and removing BOM from files...")
    
    # 检查所有模块
    modules = ["common", "gate-server", "scene-server", "login-server", "central-server", "balance-server", "test-client", "integration-test"]
    
    for module in modules:
        module_dir = os.path.join(root, module)
        if os.path.exists(module_dir):
            print(f"\nProcessing module: {module}")
            check_directory_for_bom(module_dir)
    
    # 也检查根目录中的文件
    print(f"\nProcessing root directory files...")
    check_directory_for_bom(root)
    
    print("\n✅ BOM check complete!")